if (typeof ALVEOLE.NET=="undefined")
	ALVEOLE.NET = {};

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
	ALVEOLE.NET.xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
	ALVEOLE.NET.xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
ALVEOLE.NET.handleEvent=function(event,originalEvent)
{
	jobdone=true;
	if (event.command=="set")
	{
		if (event.target=="ALVEOLE.authenticated")
			ALVEOLE.authenticated=event.data;
	}
	else
	if (event.command=="error")
	{
		if (typeof originalEvent.window!="undefined")
			originalEvent.window.setError(event.data);
		else 
			alert(event.data);
	}
	else
		jobdone=false;
	if (!jobdone)
	{
		alert("cannot parse event" + event.command + " "+event.target +" "+ event.data);
	}
};
ALVEOLE.NET.xmlhttp.onreadystatechange=function()
{
	if (ALVEOLE.NET.xmlhttp.readyState==4 && ALVEOLE.NET.xmlhttp.status==200)
	{
		try{
			res=JSON.parse(ALVEOLE.NET.xmlhttp.responseText);
			for (var i=0 ;i<res.events.length;i++)
			{
				ALVEOLE.NET.handleEvent(res.events[i],ALVEOLE.NET.xmlhttp.originalEvent);
			}
		}
		catch (err)
		{
			alert(ALVEOLE.NET.xmlhttp.responseText);
			
		}
		
	}
};
ALVEOLE.NET.event=function(command,target,data,window)
{
	this.command = command;
	this.target = target;
	this.data = data;
	this.window=window;
	return this;
};
ALVEOLE.NET.getXmlhttp=function()
{
	return ALVEOLE.NET.xmlhttp;
};
ALVEOLE.NET.sendEvent=function(event)
{
	xmlhttp=ALVEOLE.NET.getXmlhttp();
	xmlhttp.originalEvent=event;
	xmlhttp.open("POST","/alveole/service",true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("command=" + encodeURIComponent(event.command) + 
			"&target=" + encodeURIComponent(event.target) +
			"&data=" + encodeURIComponent(event.data)
			);
};
ALVEOLE.NET.connect=function(channel)
{
	sendevent("connect",channel);
};
ALVEOLE.NET.init=function(channel,window)
{
	ALVEOLE.NET.sendEvent(ALVEOLE.NET.event("Init","",channel,window));
};